<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FRP配置管理系统</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f7fa;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            text-align: center;
        }
        .header h1 {
            margin: 0 0 10px 0;
            color: #2d3748;
        }
        .header p {
            color: #4a5568;
            margin: 0;
        }
        .section {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            padding: 20px;
        }
        .section h2 {
            margin-top: 0;
            color: #2d3748;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .btn {
            display: inline-block;
            padding: 8px 16px;
            background-color: #4299e1;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            transition: background-color 0.2s;
        }
        .btn:hover {
            background-color: #3182ce;
        }
        .btn-danger {
            background-color: #e53e3e;
        }
        .btn-danger:hover {
            background-color: #c53030;
        }
        .btn-success {
            background-color: #48bb78;
        }
        .btn-success:hover {
            background-color: #38a169;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 0;
        }
        .table th,
        .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        .table th {
            background: #f8fafc;
            font-weight: 600;
            color: #4a5568;
        }
        .table tbody tr:hover {
            background-color: #f8fafc;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.875rem;
            font-weight: 500;
        }
        .status-online {
            background-color: #c6f6d5;
            color: #2f855a;
        }
        .status-offline {
            background-color: #fed7d7;
            color: #c53030;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 2px solid #e2e8f0;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            margin-bottom: -2px;
            color: #4a5568;
            transition: all 0.2s;
        }
        .tab:hover {
            color: #4299e1;
        }
        .tab.active {
            color: #4299e1;
            border-bottom-color: #4299e1;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .error-message {
            display: none;
            background-color: #fed7d7;
            color: #c53030;
            padding: 12px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        .file-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #e2e8f0;
        }
        .file-item:last-child {
            border-bottom: none;
        }
        .file-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .file-size {
            color: #718096;
            font-size: 0.875rem;
        }
        #copySuccess {
            display: none;
            position: fixed;
            top: 20px;
            right: 20px;
            background: #48bb78;
            color: white;
            padding: 10px 20px;
            border-radius: 6px;
            animation: fadeOut 2s forwards;
            animation-delay: 1s;
        }
        @keyframes fadeOut {
            to {
                opacity: 0;
            }
        }
        .config-list {
            margin-bottom: 30px;
        }
        .config-list h3 {
            color: #4a5568;
            margin: 20px 0 10px 0;
            padding-bottom: 8px;
            border-bottom: 1px solid #e2e8f0;
        }
        .config-list .table {
            margin-bottom: 30px;
        }
        #configContent {
            white-space: pre-wrap;
            font-family: monospace;
            background: #f7fafc;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        #command {
            background: #f7fafc;
            padding: 10px;
            border-radius: 4px;
            display: block;
            font-family: monospace;
        }
        .config-row {
            display: flex;
            gap: 20px;
            margin-bottom: 30px;
        }
        .config-list {
            flex: 2;
        }
        .config-form {
            flex: 1;
            padding: 15px;
            background: #f7fafc;
            border-radius: 6px;
        }
        .inline-form {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .inline-form .input {
            width: 100%;
            margin-bottom: 0;
        }
        .inline-form .btn {
            margin-top: 10px;
        }
        .section h3 {
            margin-bottom: 15px;
            color: #2d3748;
            font-size: 1.2em;
        }
        .config-generator {
            background: #f7fafc;
            padding: 20px;
            border-radius: 6px;
        }
        .config-selector {
            margin-bottom: 20px;
        }
        .select-group {
            margin-bottom: 15px;
        }
        .select-group label {
            display: block;
            margin-bottom: 5px;
            color: #4a5568;
        }
        .select-group select {
            width: 100%;
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #e2e8f0;
        }
        .help-text {
            display: block;
            margin-top: 5px;
            color: #718096;
            font-size: 0.9em;
        }
        .config-output {
            margin: 20px 0;
            padding: 15px;
            background: #fff;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: monospace;
        }
        .command-output {
            margin-top: 20px;
            padding: 15px;
            background: #fff;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
        }
        .command-output code {
            display: block;
            margin-bottom: 10px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>FRP配置管理系统</h1>
            <p>简单高效的FRP配置管理工具</p>
        </div>

        <div class="tabs">
            <div class="tab active" onclick="switchTab('status')">服务器代理状态</div>
            <div class="tab" onclick="switchTab('config')">配置管理</div>
            <div class="tab" onclick="switchTab('download')">文件下载</div>
        </div>

        <!-- 代理状态 -->
        <div id="status" class="tab-content active">
            <div class="section">
                <div class="error-message" id="statusError"></div>
                <div id="statusLoading" class="loading">加载中...</div>
                <table class="table">
                    <thead>
                        <tr>
                            <th>名称</th>
                            <th>类型</th>
                            <th>本地地址</th>
                            <th>远程端口</th>
                            <th>当前连接数</th>
                            <th>最后启动时间</th>
                            <th>状态</th>
                            <th>今日流量</th>
                        </tr>
                    </thead>
                    <tbody id="proxyList"></tbody>
                </table>
                <button onclick="refreshStatus()" class="btn">刷新状态</button>
            </div>
        </div>

        <!-- 配置管理 -->
        <div id="config" class="tab-content">
            <div class="section">
                <h2>现有配置</h2>
                <div class="config-row">
                    <div class="config-list" style="flex: 2;">
                        <h3>服务器配置</h3>
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>服务器名称</th>
                                    <th>服务器地址</th>
                                    <th>服务器端口</th>
                                    <th>认证令牌</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for config in server_configs %}
                                <tr>
                                    <td>{{ config.server_name }}</td>
                                    <td>{{ config.server_addr }}</td>
                                    <td>{{ config.server_port }}</td>
                                    <td>{{ config.token }}</td>
                                    <td>
                                        <button onclick="deleteServerConfig({{ config.id }})" class="btn btn-danger">删除</button>
                                    </td>
                                </tr>
                                {% endfor %}
                                {% if not server_configs %}
                                <tr>
                                    <td colspan="5" style="text-align: center;">暂无服务器配置</td>
                                </tr>
                                {% endif %}
                            </tbody>
                        </table>
                    </div>
                    <div class="config-form" style="flex: 1;">
                        <form id="serverConfigForm" class="inline-form">
                            <input type="text" class="input" name="server_name" placeholder="服务器名称" required>
                            <input type="text" class="input" name="server_addr" placeholder="服务器地址" required>
                            <input type="number" class="input" name="server_port" placeholder="服务器端口"  value="7000" required>
                            <input type="text" class="input" name="token" placeholder="认证令牌" required>
                            <button type="submit" class="btn">保存配置</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="section">
                <h2>客户端配置</h2>
                <div class="config-row">
                    <div class="config-list" style="flex: 2;">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>名称</th>
                                    <th>类型</th>
                                    <th>本地IP</th>
                                    <th>本地端口</th>
                                    <th>远程端口</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for config in client_configs %}
                                <tr>
                                    <td>{{ config.name }}</td>
                                    <td>{{ config.type }}</td>
                                    <td>{{ config.local_ip }}</td>
                                    <td>{{ config.local_port }}</td>
                                    <td>{{ config.remote_port }}</td>
                                    <td>
                                        <button onclick="deleteClientConfig({{ config.id }})" class="btn btn-danger">删除</button>
                                    </td>
                                </tr>
                                {% endfor %}
                                {% if not client_configs %}
                                <tr>
                                    <td colspan="6" style="text-align: center;">暂无客户端配置</td>
                                </tr>
                                {% endif %}
                            </tbody>
                        </table>
                    </div>
                    <div class="config-form" style="flex: 1;">
                        <form id="clientConfigForm" class="inline-form">
                            <input type="text" class="input" name="name" placeholder="名称" required>
                            <input type="text" class="input" name="type" placeholder="类型" value="tcp" required>
                            <input type="text" class="input" name="local_ip" placeholder="本地IP" value="127.0.0.1" required>
                            <input type="number" class="input" name="local_port" placeholder="本地端口" required>
                            <input type="number" class="input" name="remote_port" placeholder="远程端口" required>
                            <button type="submit" class="btn">保存配置</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="section">
                <h2>配置生成</h2>
                <div class="config-generator">
                    <div class="config-selector">
                        <div class="select-group">
                            <label>选择服务器配置：</label>
                            <select id="serverSelect" class="input">
                                <option value="">请选择服务器配置</option>
                                {% for config in server_configs %}
                                <option value="{{ config.id }}">{{ config.server_name }} ({{ config.server_addr }}:{{ config.server_port }})</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="select-group">
                            <label>选择客户端配置：</label>
                            <select id="clientSelect" class="input" multiple>
                                {% for config in client_configs %}
                                <option value="{{ config.id }}">{{ config.name }} ({{ config.local_ip }}:{{ config.local_port }})</option>
                                {% endfor %}
                            </select>
                            <small class="help-text">按住Ctrl键可以选择多个客户端配置</small>
                        </div>
                        <button onclick="generateSelectedConfig()" class="btn">生成配置</button>
                    </div>
                    <div id="configContent" class="config-output"></div>
                    <div id="commandDisplay" class="command-output" style="display: none;">
                        <code id="command"></code>
                        <button onclick="copyCommand()" id="copyButton" class="btn">复制命令</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 文件下载 -->
        <div id="download" class="tab-content">
            <div class="section">
                <h2>可下载文件</h2>
                <div class="file-list">
                    {% for file in files %}
                    <div class="file-item">
                        <div class="file-info">
                            <span class="file-name">{{ file.name }}</span>
                            <span class="file-size">{{ file.size }}</span>
                        </div>
                        <a href="/download/{{ file.name }}" class="btn">下载</a>
                    </div>
                    {% endfor %}
                </div>
            </div>
            <div class="section">
                <h2>帮助文档</h2>
                <p>查看 FRP 官方文档了解更多信息：<a href="https://gofrp.org/zh-cn/docs/overview/" target="_blank">FRP 文档</a></p>
            </div>
        </div>
    </div>

    <div id="copySuccess">命令已复制到剪贴板！</div>

    <script>
        // 切换标签页
        function switchTab(tabId) {
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.querySelector(`.tab[onclick="switchTab('${tabId}')"]`).classList.add('active');
            document.getElementById(tabId).classList.add('active');
        }

        // 格式化字节大小
        function formatBytes(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 刷新代理状态
        function refreshStatus() {
            const loading = document.getElementById('statusLoading');
            const errorMessage = document.getElementById('statusError');
            const proxyList = document.getElementById('proxyList');
            
            loading.style.display = 'block';
            errorMessage.style.display = 'none';
            
            fetch('/api/proxy/status')
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    proxyList.innerHTML = '';
                    
                    if (data.code === 0 && data.proxies?.proxies && Array.isArray(data.proxies.proxies)) {
                        data.proxies.proxies.forEach(proxy => {
                            const row = document.createElement('tr');
                            const remotePort = proxy.conf?.remotePort || '-';
                            const proxyName = proxy.name || '-';
                            row.innerHTML = `
                                <td>
                                    ${remotePort !== '-' ? 
                                        `<a href="http://39.104.71.213:${remotePort}/" target="_blank" style="color: #4299e1; text-decoration: none;">
                                            ${proxyName}
                                        </a>` : 
                                        proxyName
                                    }
                                </td>
                                <td>${proxy.conf?.type || '-'}</td>
                                <td>${proxy.conf?.localIP || '-'}</td>
                                <td>${remotePort}</td>
                                <td>${proxy.curConns || '0'}</td>
                                <td>${proxy.lastStartTime || '-'}</td>
                                <td><span class="status-badge ${proxy.status === 'online' ? 'status-online' : 'status-offline'}">
                                    ${proxy.status === 'online' ? '在线' : '离线'}
                                </span></td>
                                <td>${formatBytes((proxy.todayTrafficIn || 0) + (proxy.todayTrafficOut || 0))}</td>
                            `;
                            proxyList.appendChild(row);
                        });

                        if (data.proxies.proxies.length === 0) {
                            const row = document.createElement('tr');
                            row.innerHTML = '<td colspan="8" style="text-align: center;">暂无代理数据</td>';
                            proxyList.appendChild(row);
                        }
                    } else {
                        throw new Error(data.msg || '获取数据失败');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    errorMessage.style.display = 'block';
                    errorMessage.textContent = '获取代理状态失败：' + error.message;
                    proxyList.innerHTML = '<tr><td colspan="8" style="text-align: center;">获取数据失败</td></tr>';
                });
        }

        // 删除服务器配置
        function deleteServerConfig(id) {
            if (confirm('确定要删除这个服务器配置吗？')) {
                fetch(`/delete_server_config/${id}`, { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 0) {
                            window.location.href = '/?tab=config';
                        } else {
                            alert('删除失败：' + data.msg);
                        }
                    })
                    .catch(error => {
                        alert('删除失败：' + error);
                    });
            }
        }

        // 删除客户端配置
        function deleteClientConfig(id) {
            if (confirm('确定要删除这个客户端配置吗？')) {
                fetch(`/delete_client_config/${id}`, { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 0) {
                            window.location.href = '/?tab=config';
                        } else {
                            alert('删除失败：' + data.msg);
                        }
                    })
                    .catch(error => {
                        alert('删除失败：' + error);
                    });
            }
        }

        // 生成选中的配置
        function generateSelectedConfig() {
            const serverId = document.getElementById('serverSelect').value;
            const clientSelect = document.getElementById('clientSelect');
            const clientIds = Array.from(clientSelect.selectedOptions).map(option => option.value);

            if (!serverId) {
                alert('请选择服务器配置');
                return;
            }
            if (clientIds.length === 0) {
                alert('请选择至少一个客户端配置');
                return;
            }

            fetch('/generate_selected_config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    server_id: serverId,
                    client_ids: clientIds
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    document.getElementById('configContent').textContent = data.config;
                    document.getElementById('command').textContent = data.command || '';
                    document.getElementById('commandDisplay').style.display = data.command ? 'block' : 'none';
                    document.getElementById('copyButton').style.display = data.command ? 'inline-block' : 'none';
                } else {
                    alert('生成配置失败：' + data.msg);
                }
            })
            .catch(error => {
                alert('生成配置失败：' + error);
            });
        }

        // 复制命令
        function copyCommand() {
            const command = document.getElementById('command').textContent;
            navigator.clipboard.writeText(command).then(() => {
                const copySuccess = document.getElementById('copySuccess');
                copySuccess.style.display = 'block';
                copySuccess.style.opacity = '1';
                setTimeout(() => {
                    copySuccess.style.display = 'none';
                    copySuccess.style.opacity = '0';
                }, 3000);
            });
        }

        // 服务器配置表单提交
        document.getElementById('serverConfigForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const data = {
                server_name: formData.get('server_name'),
                server_addr: formData.get('server_addr'),
                server_port: parseInt(formData.get('server_port')),
                token: formData.get('token')
            };

            fetch('/add_server_config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('服务器配置保存成功！');
                    window.location.href = '/?tab=config';
                } else {
                    alert('保存失败：' + data.error);
                }
            })
            .catch(error => {
                alert('保存失败：' + error);
            });
        });

        // 客户端配置表单提交
        document.getElementById('clientConfigForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const data = {
                name: formData.get('name'),
                type: formData.get('type'),
                local_ip: formData.get('local_ip'),
                local_port: parseInt(formData.get('local_port')),
                remote_port: parseInt(formData.get('remote_port'))
            };

            fetch('/add_client_config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('客户端配置保存成功！');
                    window.location.href = '/?tab=config';
                } else {
                    alert('保存失败：' + data.error);
                }
            })
            .catch(error => {
                alert('保存失败：' + error);
            });
        });

        // 每30秒自动刷新状态
        setInterval(refreshStatus, 30000);
        
        // 页面加载时自动刷新状态
        document.addEventListener('DOMContentLoaded', function() {
            // 获取URL参数中的tab
            const urlParams = new URLSearchParams(window.location.search);
            const tab = urlParams.get('tab');
            if (tab) {
                switchTab(tab);
            }
            
            // 刷新代理状态
            refreshStatus();
        });
    </script>
</body>
</html>
